/**
 * 污染类型管理模块
 * 提供污染类型的CRUD操作、样例管理、数据导入导出等功能
 * 优化版本：改进错误处理、用户体验和功能完整性
 */

// 导入ApiService（使用延迟检查机制）
let _apiServiceInstance = null;

/**
 * 获取ApiService实例（延迟加载）
 */
window.getApiService = function() {
    if (!_apiServiceInstance) {
        if (window.ApiService && window.ApiService._isReady) {
            console.log('✅ 污染类型管理器使用全局ApiService');
            // ApiService是静态类，需要包装成实例方法
            _apiServiceInstance = {
                get: async function(url, params = {}) {
                    // 构建完整的URL和参数
                    const queryString = new URLSearchParams(params).toString();
                    const fullUrl = queryString ? `${url}?${queryString}` : url;
                    console.log('ApiService.get调用:', fullUrl);

                    try {
                        const response = await window.ApiService.request(fullUrl, {
                            method: 'GET'
                        });
                        console.log('ApiService.get响应:', response);
                        return response;
                    } catch (error) {
                        console.error('ApiService.get请求失败:', error);
                        // 改进错误处理
                        if (error.message === '[object Object]') {
                            throw new Error('网络请求失败，请检查网络连接');
                        }
                        throw error;
                    }
                },
                post: async function(url, data = {}) {
                    console.log('ApiService.post调用:', url);
                    try {
                        const response = await window.ApiService.request(url, {
                            method: 'POST',
                            body: JSON.stringify(data)
                        });
                        console.log('ApiService.post响应:', response);
                        return response;
                    } catch (error) {
                        console.error('ApiService.post请求失败:', error);
                        // 改进错误处理
                        if (error.message === '[object Object]') {
                            throw new Error('数据提交失败，请检查输入数据');
                        }
                        throw error;
                    }
                },
                put: async function(url, data = {}) {
                    console.log('ApiService.put调用:', url);
                    try {
                        const response = await window.ApiService.request(url, {
                            method: 'PUT',
                            body: JSON.stringify(data)
                        });
                        console.log('ApiService.put响应:', response);
                        return response;
                    } catch (error) {
                        console.error('ApiService.put请求失败:', error);
                        // 改进错误处理
                        if (error.message === '[object Object]') {
                            throw new Error('数据更新失败，请检查输入数据');
                        }
                        throw error;
                    }
                },
                delete: async function(url, params = {}) {
                    const queryString = new URLSearchParams(params).toString();
                    const fullUrl = queryString ? `${url}?${queryString}` : url;
                    console.log('ApiService.delete调用:', fullUrl);
                    try {
                        const response = await window.ApiService.request(fullUrl, {
                            method: 'DELETE'
                        });
                        console.log('ApiService.delete响应:', response);
                        return response;
                    } catch (error) {
                        console.error('ApiService.delete请求失败:', error);
                        // 改进错误处理
                        if (error.message === '[object Object]') {
                            throw new Error('删除操作失败，请重试');
                        }
                        throw error;
                    }
                }
            };
        } else {
            console.warn('⚠️ ApiService未就绪，使用回退实现');
            // 提供回退实现
            _apiServiceInstance = {
                get: async function(url, params = {}) {
                    const queryString = new URLSearchParams(params).toString();
                    const fullUrl = queryString ? `${url}?${queryString}` : url;

                    // 获取认证token - 优先使用authManager
                    let token = null;
                    if (window.authManager && typeof window.authManager.getToken === 'function') {
                        token = window.authManager.getToken();
                    }
                    if (!token) {
                        token = localStorage.getItem('auth_token') || localStorage.getItem('token');
                    }

                    const response = await fetch(fullUrl, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${token || ''}`
                        }
                    });
                    return await response.json();
                },
                post: async function(url, data = {}) {
                    // 获取认证token - 优先使用authManager
                    let token = null;
                    if (window.authManager && typeof window.authManager.getToken === 'function') {
                        token = window.authManager.getToken();
                    }
                    if (!token) {
                        token = localStorage.getItem('auth_token') || localStorage.getItem('token');
                    }

                    const response = await fetch(url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${token || ''}`
                        },
                        body: JSON.stringify(data)
                    });
                    return await response.json();
                },
                put: async function(url, data = {}) {
                    // 获取认证token - 优先使用authManager
                    let token = null;
                    if (window.authManager && typeof window.authManager.getToken === 'function') {
                        token = window.authManager.getToken();
                    }
                    if (!token) {
                        token = localStorage.getItem('auth_token') || localStorage.getItem('token');
                    }

                    const response = await fetch(url, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${token || ''}`
                        },
                        body: JSON.stringify(data)
                    });
                    return await response.json();
                },
                delete: async function(url, params = {}) {
                    const queryString = new URLSearchParams(params).toString();
                    const fullUrl = queryString ? `${url}?${queryString}` : url;

                    // 获取认证token - 优先使用authManager
                    let token = null;
                    if (window.authManager && typeof window.authManager.getToken === 'function') {
                        token = window.authManager.getToken();
                    }
                    if (!token) {
                        token = localStorage.getItem('auth_token') || localStorage.getItem('token');
                    }

                    const response = await fetch(fullUrl, {
                        method: 'DELETE',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${token || ''}`
                        }
                    });
                    return await response.json();
                }
            };
        }
    }
    return _apiServiceInstance;
}

// NotificationService 改进版，提供更好的用户体验
const PollutionNotificationService = window.NotificationService || {
    success: function(message) {
        console.log('Success:', message);
        this.showToast(message, 'success');
    },
    error: function(message) {
        console.error('Error:', message);
        this.showToast(message, 'error');
    },
    info: function(message) {
        console.log('Info:', message);
        this.showToast(message, 'info');
    },
    warning: function(message) {
        console.warn('Warning:', message);
        this.showToast(message, 'warning');
    },
    showToast: function(message, type = 'info') {
        // 移除已存在的相同类型的通知
        const existingToasts = document.querySelectorAll(`.toast-${type}`);
        existingToasts.forEach(toast => toast.remove());

        const toast = document.createElement('div');
        const bgColor = {
            success: 'bg-green-500',
            error: 'bg-red-500',
            warning: 'bg-yellow-500',
            info: 'bg-blue-500'
        }[type] || 'bg-gray-500';

        toast.className = `fixed top-4 right-4 ${bgColor} text-white px-6 py-3 rounded-lg shadow-lg z-50 toast-${type} transform transition-all duration-300 translate-x-full opacity-0`;
        toast.textContent = message;

        // 添加关闭按钮
        const closeBtn = document.createElement('button');
        closeBtn.innerHTML = '×';
        closeBtn.className = 'ml-4 text-white hover:text-gray-200';
        closeBtn.onclick = () => toast.remove();
        toast.appendChild(closeBtn);

        document.body.appendChild(toast);

        // 显示动画
        setTimeout(() => {
            toast.classList.remove('translate-x-full', 'opacity-0');
        }, 10);

        // 自动移除
        setTimeout(() => {
            toast.classList.add('translate-x-full', 'opacity-0');
            setTimeout(() => toast.remove(), 300);
        }, 5000);
    }
};

class PollutionTypesManager {
    constructor() {
        this.currentTypes = [];
        this.currentExamples = {};
        this.editingTypeId = null;
        this.editingExampleId = null;
        this.currentCustomerId = "default";
        this.isLoading = false; // 添加加载状态
        this.init();
    }

    init() {
        this.bindEvents();
        // 不立即加载数据，等待延迟初始化
        console.log('污染类型管理器初始化完成，等待延迟初始化...');
    }

    /**
     * 延迟初始化 - 确保所有依赖就绪后调用
     */
    async delayedInit() {
        console.log('开始延迟初始化污染类型管理器...');

        try {
            // 检查必要依赖
            const apiService = getApiService();
            if (!apiService) {
                console.error('ApiService不可用，延迟初始化失败');
                return false;
            }

            // 检查必要DOM元素
            const container = document.getElementById('pollutionTypesTableContainer');
            if (!container) {
                console.warn('污染类型容器不存在，可能当前不在污染类型标签页');
                return true; // 返回true但不加载数据
            }

            // 开始加载数据
            await this.loadPollutionTypes();

            console.log('污染类型管理器延迟初始化完成');
            return true;
        } catch (error) {
            console.error('污染类型管理器延迟初始化失败:', error);
            return false;
        }
    }

    bindEvents() {
        // 搜索功能 - 增强的防抖搜索
        const searchInput = document.getElementById('searchKeyword');
        let searchTimeout;

        searchInput?.addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                this.searchPollutionTypes();
            }, 500); // 500ms防抖
        });

        searchInput?.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                clearTimeout(searchTimeout);
                this.searchPollutionTypes();
            }
        });

        // 视图模式切换
        document.getElementById('viewMode')?.addEventListener('change', () => {
            this.loadPollutionTypes();
        });

        // 激活状态过滤
        document.getElementById('activeFilter')?.addEventListener('change', () => {
            this.loadPollutionTypes();
        });

        // 绑定批量操作事件
        this.bindBatchOperations();

        // 绑定快捷键
        this.bindKeyboardShortcuts();
    }

    bindBatchOperations() {
        // 批量选择
        document.addEventListener('change', (e) => {
            if (e.target.classList.contains('batch-select')) {
                this.updateBatchSelectionUI();
            }
        });

        // 全选/取消全选
        const selectAllCheckbox = document.getElementById('selectAllTypes');
        if (selectAllCheckbox) {
            selectAllCheckbox.addEventListener('change', (e) => {
                const checkboxes = document.querySelectorAll('.batch-select');
                checkboxes.forEach(cb => cb.checked = e.target.checked);
                this.updateBatchSelectionUI();
            });
        }

        // 批量删除
        const batchDeleteBtn = document.getElementById('batchDeleteBtn');
        if (batchDeleteBtn) {
            batchDeleteBtn.addEventListener('click', () => {
                this.batchDeletePollutionTypes();
            });
        }

        // 批量激活/停用
        const batchActivateBtn = document.getElementById('batchActivateBtn');
        const batchDeactivateBtn = document.getElementById('batchDeactivateBtn');

        if (batchActivateBtn) {
            batchActivateBtn.addEventListener('click', () => {
                this.batchTogglePollutionTypes(true);
            });
        }

        if (batchDeactivateBtn) {
            batchDeactivateBtn.addEventListener('click', () => {
                this.batchTogglePollutionTypes(false);
            });
        }
    }

    bindKeyboardShortcuts() {
        document.addEventListener('keydown', (e) => {
            // Ctrl/Cmd + F: 聚焦搜索框
            if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
                e.preventDefault();
                const searchInput = document.getElementById('searchKeyword');
                if (searchInput) {
                    searchInput.focus();
                    searchInput.select();
                }
            }

            // Ctrl/Cmd + N: 新建污染类型
            if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
                e.preventDefault();
                if (window.pollutionTypesManager) {
                    window.pollutionTypesManager.showCreatePollutionTypeModal();
                }
            }

            // F5: 刷新数据
            if (e.key === 'F5') {
                e.preventDefault();
                if (window.pollutionTypesManager) {
                    window.pollutionTypesManager.refreshData();
                }
            }
        });
    }

    async loadStatistics() {
        try {
            console.log('加载统计数据...');
            const response = await getApiService().get('/api/pollution-types/statistics', {
                customer_id: this.currentCustomerId
            });

            console.log('统计数据响应:', response);

            if (response && response.success === true) {
                const data = response.data || {};
                this.updateStatisticsDisplay(data);
            } else {
                console.error('统计数据API响应异常:', response);
                // 静默失败，不显示错误给用户
            }
        } catch (error) {
            console.error('加载统计数据失败:', error);
            // 静默失败，不显示错误给用户
        }
    }

    updateStatisticsDisplay(data) {
        // 更新统计数据显示，带有动画效果
        const updateElement = (id, value) => {
            const element = document.getElementById(id);
            if (element) {
                const oldValue = parseInt(element.textContent) || 0;
                const newValue = parseInt(value) || 0;
                if (oldValue !== newValue) {
                    element.style.transform = 'scale(1.1)';
                    element.textContent = newValue;
                    setTimeout(() => {
                        element.style.transform = 'scale(1)';
                    }, 200);
                }
            }
        };

        updateElement('totalTypesCount', data.types_total);
        updateElement('activeTypesCount', data.types_active);
        updateElement('totalExamplesCount', data.examples_total);
        updateElement('typesWithExamplesCount', data.types_with_examples);
    }

    async loadPollutionTypes() {
        const container = document.getElementById('pollutionTypesTableContainer');
        if (!container) {
            console.warn('污染类型容器不存在，跳过加载');
            return;
        }

        // 显示加载状态
        this.setLoadingState(true);
        container.innerHTML = this.getLoadingHTML();

        try {
            const viewMode = document.getElementById('viewMode')?.value || 'list';
            const activeOnly = document.getElementById('activeFilter')?.value === 'true';
            const keyword = document.getElementById('searchKeyword')?.value || '';

            console.log('加载污染类型数据:', { viewMode, activeOnly, keyword });

            let response;
            if (viewMode === 'tree') {
                response = await getApiService().get('/api/pollution-types', {
                    tree_view: true,
                    active_only: activeOnly,
                    customer_id: this.currentCustomerId
                });
            } else {
                response = await getApiService().get('/api/pollution-types', {
                    keyword: keyword,
                    active_only: activeOnly,
                    customer_id: this.currentCustomerId
                });
            }

            console.log('API响应:', response);

            if (response && response.success === true) {
                this.currentTypes = response.data || [];
                if (viewMode === 'tree') {
                    this.renderTreeView(this.currentTypes);
                } else {
                    this.renderListView(this.currentTypes);
                }
                // 加载统计数据
                this.loadStatistics();
            } else {
                console.error('API响应异常:', response);
                container.innerHTML = this.getErrorHTML(
                    '加载数据失败',
                    this.formatErrorMessage(response?.message || '服务器响应异常')
                );
                PollutionNotificationService.error(this.formatErrorMessage(response?.message || '加载数据失败'));
            }
        } catch (error) {
            console.error('加载污染类型失败:', error);
            const errorMsg = this.formatErrorMessage(error.message);
            container.innerHTML = this.getErrorHTML('网络请求失败', errorMsg);
            PollutionNotificationService.error(errorMsg);
        } finally {
            this.setLoadingState(false);
        }
    }

    renderListView(types) {
        const container = document.getElementById('pollutionTypesTableContainer');

        if (types.length === 0) {
            container.innerHTML = `
                <div class="text-center py-12">
                    <i class="fas fa-inbox text-gray-300 text-4xl mb-4"></i>
                    <p class="text-gray-500">暂无污染类型数据</p>
                    <button onclick="pollutionTypesManager.showCreatePollutionTypeModal()" class="mt-4 bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 transition-colors">
                        <i class="fas fa-plus mr-2"></i>创建第一个污染类型
                    </button>
                </div>
            `;
            return;
        }

        const table = `
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left w-12">
                                <input type="checkbox" id="selectAllTypes" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500" title="全选/取消全选">
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">代码</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">层级</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">父级代码</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">样例数量</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        ${types.map(type => this.renderTypeRow(type)).join('')}
                    </tbody>
                </table>
            </div>

            <!-- 批量操作工具栏 -->
            <div class="mt-4 p-4 bg-gray-50 rounded-lg border border-gray-200">
                <div class="flex items-center justify-between">
                    <div class="flex items-center space-x-4">
                        <span class="text-sm text-gray-600">已选择 <span id="selectedCount">0</span> 项</span>
                        <button id="batchDeleteBtn" class="bg-red-500 text-white px-3 py-1 rounded text-sm hover:bg-red-600 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors" disabled>
                            <i class="fas fa-trash mr-1"></i>删除 (0)
                        </button>
                        <button id="batchActivateBtn" class="bg-green-500 text-white px-3 py-1 rounded text-sm hover:bg-green-600 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors" disabled>
                            <i class="fas fa-check mr-1"></i>激活 (0)
                        </button>
                        <button id="batchDeactivateBtn" class="bg-yellow-500 text-white px-3 py-1 rounded text-sm hover:bg-yellow-600 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors" disabled>
                            <i class="fas fa-pause mr-1"></i>停用 (0)
                        </button>
                    </div>
                    <div class="text-xs text-gray-500">
                        提示：使用 Ctrl+F 搜索，Ctrl+N 新建，F5 刷新
                    </div>
                </div>
            </div>
        `;

        container.innerHTML = table;

        // 重新绑定批量操作事件
        this.bindBatchOperations();
    }

    renderTreeView(treeData) {
        const container = document.getElementById('pollutionTypesTableContainer');

        if (treeData.length === 0) {
            container.innerHTML = `
                <div class="text-center py-12">
                    <i class="fas fa-inbox text-gray-300 text-4xl mb-4"></i>
                    <p class="text-gray-500">暂无污染类型数据</p>
                </div>
            `;
            return;
        }

        const treeHtml = `
            <div class="p-6">
                ${treeData.map(node => this.renderTreeNode(node, 0)).join('')}
            </div>
        `;

        container.innerHTML = treeHtml;

        // 绑定树节点展开/收起事件
        container.querySelectorAll('.tree-toggle').forEach(toggle => {
            toggle.addEventListener('click', (e) => {
                e.stopPropagation();
                const children = e.target.closest('.tree-node').querySelector('.tree-children');
                if (children) {
                    children.classList.toggle('hidden');
                    e.target.classList.toggle('fa-chevron-right');
                    e.target.classList.toggle('fa-chevron-down');
                }
            });
        });
    }

    renderTreeNode(node, level) {
        const hasChildren = node.children && node.children.length > 0;
        const indent = level * 20;

        return `
            <div class="tree-node mb-2">
                <div class="flex items-center p-2 hover:bg-gray-50 rounded cursor-pointer" style="margin-left: ${indent}px">
                    ${hasChildren ? '<i class="fas fa-chevron-right tree-toggle mr-2 text-gray-400"></i>' : '<span class="mr-4"></span>'}
                    <div class="flex-1">
                        <div class="flex items-center justify-between">
                            <div>
                                <span class="font-medium">${node.name}</span>
                                <span class="text-sm text-gray-500 ml-2">(${node.code})</span>
                                <span class="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded ml-2">L${node.level}</span>
                            </div>
                            <div class="flex items-center space-x-2">
                                <button onclick="pollutionTypesManager.showExamplesModal(${node.id})" class="text-purple-600 hover:text-purple-800 text-sm">
                                    <i class="fas fa-list-alt mr-1"></i>样例
                                </button>
                                <button onclick="pollutionTypesManager.editPollutionType(${node.id})" class="text-blue-600 hover:text-blue-800 text-sm">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button onclick="pollutionTypesManager.deletePollutionType(${node.id})" class="text-red-600 hover:text-red-800 text-sm">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                ${hasChildren ? `
                    <div class="tree-children hidden">
                        ${node.children.map(child => this.renderTreeNode(child, level + 1)).join('')}
                    </div>
                ` : ''}
            </div>
        `;
    }

    renderTypeRow(type) {
        const statusClass = type.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800';
        const statusText = type.is_active ? '激活' : '停用';
        const rowId = `type-row-${type.id}`;

        return `
            <tr id="${rowId}" class="hover:bg-gray-50 transition-colors">
                <td class="px-6 py-4 whitespace-nowrap w-12">
                    <input type="checkbox" value="${type.id}" class="batch-select rounded border-gray-300 text-blue-600 focus:ring-blue-500" title="选择此项">
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                    <div class="flex items-center">
                        <span class="font-mono text-xs bg-gray-100 px-2 py-1 rounded mr-2">${type.code}</span>
                        ${type.display_name ? `<span class="text-gray-400 text-xs">(${type.display_name})</span>` : ''}
                    </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    <div class="font-medium">${type.name}</div>
                    ${type.description ? `<div class="text-xs text-gray-500 mt-1 max-w-xs truncate">${type.description}</div>` : ''}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                        L${type.level}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${type.parent_code || '-'}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    <div class="flex items-center">
                        <span class="mr-2">${type.examples_count || 0}</span>
                        ${type.examples_count > 0 ? `
                            <button onclick="pollutionTypesManager.showExamplesModal(${type.id})" class="text-purple-600 hover:text-purple-800 text-xs" title="查看样例">
                                <i class="fas fa-eye"></i>
                            </button>
                        ` : ''}
                    </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full ${statusClass}">
                        ${statusText}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div class="flex items-center space-x-1">
                        <button onclick="pollutionTypesManager.showExamplesModal(${type.id})" class="text-purple-600 hover:text-purple-800 p-1 rounded hover:bg-purple-50 transition-colors" title="管理样例">
                            <i class="fas fa-list-alt text-sm"></i>
                        </button>
                        <button onclick="pollutionTypesManager.editPollutionType(${type.id})" class="text-blue-600 hover:text-blue-800 p-1 rounded hover:bg-blue-50 transition-colors" title="编辑">
                            <i class="fas fa-edit text-sm"></i>
                        </button>
                        <button onclick="pollutionTypesManager.deletePollutionType(${type.id})" class="text-red-600 hover:text-red-800 p-1 rounded hover:bg-red-50 transition-colors" title="删除">
                            <i class="fas fa-trash text-sm"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    }

    async searchPollutionTypes() {
        const searchKeyword = document.getElementById('searchKeyword')?.value.trim();

        if (searchKeyword) {
            console.log('搜索污染类型:', searchKeyword);
        }

        this.loadPollutionTypes();
    }

    updateBatchSelectionUI() {
        const selectedCheckboxes = document.querySelectorAll('.batch-select:checked');
        const count = selectedCheckboxes.length;
        const totalCount = document.querySelectorAll('.batch-select').length;

        // 更新全选框状态
        const selectAllCheckbox = document.getElementById('selectAllTypes');
        if (selectAllCheckbox) {
            if (count === 0) {
                selectAllCheckbox.indeterminate = false;
                selectAllCheckbox.checked = false;
            } else if (count === totalCount) {
                selectAllCheckbox.indeterminate = false;
                selectAllCheckbox.checked = true;
            } else {
                selectAllCheckbox.indeterminate = true;
                selectAllCheckbox.checked = false;
            }
        }

        // 更新批量操作按钮状态
        const batchButtons = ['batchDeleteBtn', 'batchActivateBtn', 'batchDeactivateBtn'];
        batchButtons.forEach(btnId => {
            const btn = document.getElementById(btnId);
            if (btn) {
                btn.disabled = count === 0;
                btn.textContent = btn.textContent.replace(/\d+/, count);
            }
        });
    }

    async batchDeletePollutionTypes() {
        const selectedCheckboxes = document.querySelectorAll('.batch-select:checked');
        const selectedIds = Array.from(selectedCheckboxes).map(cb => parseInt(cb.value));

        if (selectedIds.length === 0) {
            PollutionNotificationService.warning('请先选择要删除的污染类型');
            return;
        }

        this.confirmAction(
            `确定要删除选中的 ${selectedIds.length} 个污染类型吗？此操作不可恢复。`,
            async () => {
                try {
                    const response = await getApiService().post('/api/pollution-types/batch-delete', {
                        ids: selectedIds,
                        customer_id: this.currentCustomerId
                    });

                    if (response.success === true) {
                        const result = response.data;
                        PollutionNotificationService.success(
                            `批量删除完成：成功${result.deleted_count || 0}个，失败${result.failed_count || 0}个`
                        );
                        this.loadPollutionTypes();
                    } else {
                        const errorMsg = this.formatErrorMessage(response?.message || '批量删除失败');
                        PollutionNotificationService.error(errorMsg);
                    }
                } catch (error) {
                    console.error('批量删除失败:', error);
                    const errorMsg = this.formatErrorMessage(error.message);
                    PollutionNotificationService.error(errorMsg);
                }
            }
        );
    }

    async batchTogglePollutionTypes(activate) {
        const selectedCheckboxes = document.querySelectorAll('.batch-select:checked');
        const selectedIds = Array.from(selectedCheckboxes).map(cb => parseInt(cb.value));

        if (selectedIds.length === 0) {
            PollutionNotificationService.warning('请先选择要操作的污染类型');
            return;
        }

        const action = activate ? '激活' : '停用';

        this.confirmAction(
            `确定要${action}选中的 ${selectedIds.length} 个污染类型吗？`,
            async () => {
                try {
                    const response = await getApiService().post('/api/pollution-types/batch-toggle', {
                        ids: selectedIds,
                        is_active: activate,
                        customer_id: this.currentCustomerId
                    });

                    if (response.success === true) {
                        const result = response.data;
                        PollutionNotificationService.success(
                            `批量${action}完成：成功${result.updated_count || 0}个，失败${result.failed_count || 0}个`
                        );
                        this.loadPollutionTypes();
                    } else {
                        const errorMsg = this.formatErrorMessage(response?.message || `批量${action}失败`);
                        PollutionNotificationService.error(errorMsg);
                    }
                } catch (error) {
                    console.error(`批量${action}失败:`, error);
                    const errorMsg = this.formatErrorMessage(error.message);
                    PollutionNotificationService.error(errorMsg);
                }
            }
        );
    }

    showCreatePollutionTypeModal() {
        this.editingTypeId = null;
        document.getElementById('modalTitle').textContent = '新增污染类型';
        document.getElementById('pollutionTypeForm').reset();
        document.getElementById('pollutionTypeModal').classList.remove('hidden');
    }

    async editPollutionType(typeId) {
        try {
            const response = await getApiService().get(`/api/pollution-types/${typeId}`, {
                customer_id: this.currentCustomerId
            });

            if (response.success === true) {
                const type = response.data;
                this.editingTypeId = typeId;

                document.getElementById('modalTitle').textContent = '编辑污染类型';
                document.getElementById('typeCode').value = type.code;
                document.getElementById('typeName').value = type.name;
                document.getElementById('parentTypeCode').value = type.parent_code || '';
                document.getElementById('typeLevel').value = type.level;
                document.getElementById('tagCategory').value = type.tag_category || '';
                document.getElementById('displayName').value = type.display_name || '';
                document.getElementById('usageScope').value = type.usage_scope || '';
                document.getElementById('exclusionScope').value = type.exclusion_scope || '';
                document.getElementById('sortOrder').value = type.sort_order;
                document.getElementById('description').value = type.description || '';
                document.getElementById('isActive').value = type.is_active.toString();

                document.getElementById('pollutionTypeModal').classList.remove('hidden');
            }
        } catch (error) {
            console.error('获取污染类型详情失败:', error);
            PollutionNotificationService.error('获取污染类型详情失败');
        }
    }

    async savePollutionType(event) {
        event.preventDefault();

        // 客户端验证
        const validationError = this.validatePollutionTypeForm(event.target);
        if (validationError) {
            PollutionNotificationService.warning(validationError);
            return;
        }

        const formData = new FormData(event.target);
        const data = Object.fromEntries(formData.entries());

        // 转换布尔值和数字
        data.level = parseInt(data.level);
        data.sort_order = parseInt(data.sort_order);
        data.is_active = data.is_active === 'true';
        data.customer_id = this.currentCustomerId;

        // 显示保存状态
        const submitBtn = event.target.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>保存中...';

        try {
            let response;
            if (this.editingTypeId) {
                response = await getApiService().put(`/api/pollution-types/${this.editingTypeId}`, data);
            } else {
                response = await getApiService().post('/api/pollution-types', data);
            }

            if (response.success === true) {
                PollutionNotificationService.success(this.editingTypeId ? '污染类型更新成功' : '污染类型创建成功');
                this.closePollutionTypeModal();
                this.loadPollutionTypes();
            } else {
                const errorMsg = this.formatErrorMessage(response?.message || '保存失败');
                PollutionNotificationService.error(errorMsg);
            }
        } catch (error) {
            console.error('保存污染类型失败:', error);
            const errorMsg = this.formatErrorMessage(error.message);
            PollutionNotificationService.error(errorMsg);
        } finally {
            submitBtn.disabled = false;
            submitBtn.textContent = originalText;
        }
    }

    async deletePollutionType(typeId) {
        this.confirmAction(
            '确定要删除这个污染类型吗？如果存在子类型，将无法删除。此操作不可恢复。',
            async () => {
                try {
                    const response = await getApiService().delete(`/api/pollution-types/${typeId}`, {
                        customer_id: this.currentCustomerId
                    });

                    if (response.success === true) {
                        PollutionNotificationService.success('污染类型删除成功');
                        this.loadPollutionTypes();
                    } else {
                        const errorMsg = this.formatErrorMessage(response?.message || '删除失败');
                        PollutionNotificationService.error(errorMsg);
                    }
                } catch (error) {
                    console.error('删除污染类型失败:', error);
                    const errorMsg = this.formatErrorMessage(error.message);
                    PollutionNotificationService.error(errorMsg);
                }
            }
        );
    }

    closePollutionTypeModal() {
        document.getElementById('pollutionTypeModal').classList.add('hidden');
        this.editingTypeId = null;
    }

    async showExamplesModal(typeId) {
        try {
            // 显示加载状态
            const modalTitle = document.getElementById('examplesModalTitle');
            const originalTitle = modalTitle.textContent;
            modalTitle.textContent = '加载中...';

            const typeResponse = await getApiService().get(`/api/pollution-types/${typeId}`, {
                customer_id: this.currentCustomerId
            });

            const examplesResponse = await getApiService().get(`/api/pollution-types/${typeId}/examples`, {
                customer_id: this.currentCustomerId,
                active_only: false
            });

            if (typeResponse.success === true && examplesResponse.success === true) {
                const type = typeResponse.data;
                const examples = examplesResponse.data || [];

                modalTitle.textContent = `样例管理 - ${type.name}`;
                this.currentExamples[typeId] = examples;
                this.renderExamplesList(examples, typeId);

                document.getElementById('examplesModal').classList.remove('hidden');
            } else {
                modalTitle.textContent = originalTitle;
                const errorMsg = this.formatErrorMessage(
                    typeResponse?.message || examplesResponse?.message || '加载样例失败'
                );
                PollutionNotificationService.error(errorMsg);
            }
        } catch (error) {
            console.error('加载样例失败:', error);
            const errorMsg = this.formatErrorMessage(error.message);
            PollutionNotificationService.error(errorMsg);
        }
    }

    renderExamplesList(examples, typeId) {
        const container = document.getElementById('examplesList');

        if (examples.length === 0) {
            container.innerHTML = `
                <div class="text-center py-8">
                    <i class="fas fa-inbox text-gray-300 text-2xl mb-2"></i>
                    <p class="text-gray-500">暂无样例数据</p>
                </div>
            `;
            return;
        }

        const examplesHtml = examples.map(example => {
            const statusClass = example.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800';
            const statusText = example.is_active ? '激活' : '停用';

            return `
                <div class="bg-white border border-gray-200 rounded-lg p-3">
                    <div class="flex justify-between items-start">
                        <div class="flex-1">
                            <p class="text-sm text-gray-800 mb-2">${example.example_content}</p>
                            ${example.judgment_basis ? `<p class="text-xs text-gray-600 mb-1"><strong>判断依据:</strong> ${example.judgment_basis}</p>` : ''}
                            ${example.keywords && example.keywords.length > 0 ? `
                                <p class="text-xs text-gray-600 mb-1">
                                    <strong>关键词:</strong>
                                    <span class="inline-flex flex-wrap gap-1">
                                        ${example.keywords.map(keyword => `<span class="bg-blue-100 text-blue-800 px-1 py-0.5 rounded text-xs">${keyword}</span>`).join('')}
                                    </span>
                                </p>
                            ` : ''}
                            <div class="flex items-center space-x-4 text-xs text-gray-500">
                                <span>置信度: ${(example.confidence_level * 100).toFixed(0)}%</span>
                                <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full ${statusClass}">
                                    ${statusText}
                                </span>
                            </div>
                        </div>
                        <div class="flex space-x-1 ml-2">
                            <button onclick="pollutionTypesManager.editExample(${example.id}, ${typeId})" class="text-blue-600 hover:text-blue-800 text-sm">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button onclick="pollutionTypesManager.deleteExample(${example.id}, ${typeId})" class="text-red-600 hover:text-red-800 text-sm">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `;
        }).join('');

        container.innerHTML = examplesHtml;
    }

    showCreateExampleModal(typeId) {
        this.editingExampleId = null;
        document.getElementById('exampleModalTitle').textContent = '新增样例';
        document.getElementById('exampleForm').reset();
        document.getElementById('confidenceLevel').value = '0.8';
        document.getElementById('exampleIsActive').value = 'true';

        // 设置隐藏的typeId
        document.getElementById('exampleForm').dataset.typeId = typeId;

        document.getElementById('exampleModal').classList.remove('hidden');
    }

    async editExample(exampleId, typeId) {
        try {
            const examples = this.currentExamples[typeId] || [];
            const example = examples.find(ex => ex.id === exampleId);

            if (!example) return;

            this.editingExampleId = exampleId;

            document.getElementById('exampleModalTitle').textContent = '编辑样例';
            document.getElementById('exampleContent').value = example.example_content;
            document.getElementById('judgmentBasis').value = example.judgment_basis || '';
            document.getElementById('keywords').value = example.keywords.join(', ');
            document.getElementById('confidenceLevel').value = example.confidence_level;
            document.getElementById('exampleIsActive').value = example.is_active.toString();

            document.getElementById('exampleForm').dataset.typeId = typeId;
            document.getElementById('exampleModal').classList.remove('hidden');
        } catch (error) {
            console.error('编辑样例失败:', error);
            PollutionNotificationService.error('编辑样例失败');
        }
    }

    async saveExample(event) {
        event.preventDefault();

        // 客户端验证
        const validationError = this.validateExampleForm(event.target);
        if (validationError) {
            PollutionNotificationService.warning(validationError);
            return;
        }

        const formData = new FormData(event.target);
        const data = Object.fromEntries(formData.entries());
        const typeId = parseInt(event.target.dataset.typeId);

        // 转换数据类型
        data.confidence_level = parseFloat(data.confidence_level);
        data.is_active = data.is_active === 'true';
        data.pollution_type_id = typeId;
        data.customer_id = this.currentCustomerId;

        // 处理关键词
        if (data.keywords) {
            data.keywords = data.keywords.split(',').map(k => k.trim()).filter(k => k);
        } else {
            data.keywords = [];
        }

        // 显示保存状态
        const submitBtn = event.target.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>保存中...';

        try {
            let response;
            if (this.editingExampleId) {
                response = await getApiService().put(`/api/pollution-types/examples/${this.editingExampleId}`, data);
            } else {
                response = await getApiService().post(`/api/pollution-types/${typeId}/examples`, data);
            }

            if (response.success === true) {
                PollutionNotificationService.success(this.editingExampleId ? '样例更新成功' : '样例创建成功');
                this.closeExampleModal();

                // 重新加载样例列表
                this.showExamplesModal(typeId);
            } else {
                const errorMsg = this.formatErrorMessage(response?.message || '保存失败');
                PollutionNotificationService.error(errorMsg);
            }
        } catch (error) {
            console.error('保存样例失败:', error);
            const errorMsg = this.formatErrorMessage(error.message);
            PollutionNotificationService.error(errorMsg);
        } finally {
            submitBtn.disabled = false;
            submitBtn.textContent = originalText;
        }
    }

    async deleteExample(exampleId, typeId) {
        this.confirmAction(
            '确定要删除这个样例吗？此操作不可恢复。',
            async () => {
                try {
                    const response = await getApiService().delete(`/api/pollution-types/examples/${exampleId}`, {
                        customer_id: this.currentCustomerId
                    });

                    if (response.success === true) {
                        PollutionNotificationService.success('样例删除成功');
                        this.showExamplesModal(typeId); // 重新加载
                    } else {
                        const errorMsg = this.formatErrorMessage(response?.message || '删除失败');
                        PollutionNotificationService.error(errorMsg);
                    }
                } catch (error) {
                    console.error('删除样例失败:', error);
                    const errorMsg = this.formatErrorMessage(error.message);
                    PollutionNotificationService.error(errorMsg);
                }
            }
        );
    }

    closeExamplesModal() {
        document.getElementById('examplesModal').classList.add('hidden');
    }

    closeExampleModal() {
        document.getElementById('exampleModal').classList.add('hidden');
        this.editingExampleId = null;
    }

    showBatchCreateModal() {
        document.getElementById('batchCreateModal').classList.remove('hidden');
    }

    closeBatchCreateModal() {
        document.getElementById('batchCreateModal').classList.add('hidden');
        document.getElementById('batchCreateData').value = '';
    }

    async batchCreatePollutionTypes() {
        const dataText = document.getElementById('batchCreateData').value.trim();

        if (!dataText) {
            PollutionNotificationService.warning('请输入JSON格式的污染类型数据');
            return;
        }

        try {
            const typesData = JSON.parse(dataText);

            // 验证数据格式
            if (!Array.isArray(typesData)) {
                PollutionNotificationService.warning('数据必须是数组格式');
                return;
            }

            if (typesData.length === 0) {
                PollutionNotificationService.warning('数据数组不能为空');
                return;
            }

            if (typesData.length > 100) {
                PollutionNotificationService.warning('单次批量创建不能超过100条数据');
                return;
            }

            // 显示创建进度
            const submitBtn = document.querySelector('#batchCreateModal button[onclick="batchCreatePollutionTypes()"]');
            const originalText = submitBtn.textContent;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>创建中...';

            const response = await getApiService().post('/api/pollution-types/batch', {
                types: typesData,
                customer_id: this.currentCustomerId
            });

            if (response.success === true) {
                const result = response.data;
                const successCount = result.created_count || 0;
                const failedCount = result.failed_count || 0;

                PollutionNotificationService.success(
                    `批量创建完成：成功${successCount}个，失败${failedCount}个`
                );

                if (failedCount > 0 && result.failed_items) {
                    const errorDetails = result.failed_items.slice(0, 3).map(item =>
                        `${item.code || item.name}: ${item.error || '未知错误'}`
                    ).join('\n');

                    if (result.failed_items.length > 3) {
                        PollutionNotificationService.warning(
                            `部分创建失败：\n${errorDetails}\n...等${result.failed_items.length}个错误`
                        );
                    } else {
                        PollutionNotificationService.warning(`部分创建失败：\n${errorDetails}`);
                    }
                }

                this.closeBatchCreateModal();
                this.loadPollutionTypes();
            } else {
                const errorMsg = this.formatErrorMessage(response?.message || '批量创建失败');
                PollutionNotificationService.error(errorMsg);
            }

        } catch (error) {
            console.error('批量创建失败:', error);
            if (error instanceof SyntaxError) {
                PollutionNotificationService.error('JSON格式错误，请检查数据格式');
            } else {
                const errorMsg = this.formatErrorMessage(error.message);
                PollutionNotificationService.error(errorMsg);
            }
        } finally {
            const submitBtn = document.querySelector('#batchCreateModal button[onclick="batchCreatePollutionTypes()"]');
            if (submitBtn) {
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            }
        }
    }

    showImportModal() {
        document.getElementById('importModal').classList.remove('hidden');
    }

    closeImportModal() {
        document.getElementById('importModal').classList.add('hidden');
        document.getElementById('importForm').reset();
    }

    async importPollutionTypes(event) {
        event.preventDefault();

        const formData = new FormData(event.target);
        const file = formData.get('importFile');
        const clearExisting = formData.get('clearExisting') === 'on';

        if (!file) {
            PollutionNotificationService.warning('请选择要导入的Excel文件');
            return;
        }

        // 验证文件类型
        const allowedTypes = ['.xlsx', '.xls', '.csv'];
        const fileName = file.name.toLowerCase();
        const isValidFile = allowedTypes.some(type => fileName.endsWith(type));

        if (!isValidFile) {
            PollutionNotificationService.warning('请选择有效的Excel文件（.xlsx、.xls或.csv）');
            return;
        }

        // 验证文件大小（最大10MB）
        if (file.size > 10 * 1024 * 1024) {
            PollutionNotificationService.warning('文件大小不能超过10MB');
            return;
        }

        // 显示导入进度
        const submitBtn = event.target.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>导入中...';

        try {
            PollutionNotificationService.info('正在导入数据，请稍候...');

            // 构建导入请求数据
            const importData = new FormData();
            importData.append('file', file);
            importData.append('clear_existing', clearExisting);
            importData.append('customer_id', this.currentCustomerId);

            // 获取认证token - 优先使用authManager
            let token = null;
            if (window.authManager && typeof window.authManager.getToken === 'function') {
                token = window.authManager.getToken();
            }
            if (!token) {
                token = localStorage.getItem('auth_token') || localStorage.getItem('token');
            }

            const response = await fetch('/api/pollution-types/import', {
                method: 'POST',
                body: importData,
                headers: {
                    'Authorization': `Bearer ${token || ''}`
                }
            });

            const result = await response.json();

            if (result.success === true || result.code === 200) {
                const importResult = result.data || {};
                const message = `导入完成：成功${importResult.success_count || 0}条，失败${importResult.failed_count || 0}条`;

                PollutionNotificationService.success(message);

                if (importResult.failed_count > 0) {
                    // 显示详细错误信息
                    const errors = importResult.errors || [];
                    const errorMsg = errors.slice(0, 3).join('\n');
                    if (errors.length > 3) {
                        PollutionNotificationService.warning(`部分导入失败：${errorMsg}\n...等${errors.length}个错误`);
                    } else if (errorMsg) {
                        PollutionNotificationService.warning(`部分导入失败：${errorMsg}`);
                    }
                }

                this.closeImportModal();
                this.loadPollutionTypes();
                this.loadStatistics();
            } else {
                const errorMsg = this.formatErrorMessage(result?.message || '导入失败');
                PollutionNotificationService.error(errorMsg);
            }

        } catch (error) {
            console.error('导入失败:', error);
            const errorMsg = this.formatErrorMessage(error.message);
            PollutionNotificationService.error(errorMsg);
        } finally {
            submitBtn.disabled = false;
            submitBtn.textContent = originalText;
        }
    }

    async exportPollutionTypes() {
        try {
            PollutionNotificationService.info('正在准备导出数据...');

            // 获取认证token - 优先使用authManager
            let token = null;
            console.log('开始获取token...');

            // 检查authManager是否可用
            if (window.authManager) {
                console.log('authManager已加载');
                if (typeof window.authManager.getToken === 'function') {
                    console.log('authManager.getToken方法可用');
                    token = window.authManager.getToken();
                    console.log('从authManager获取token结果:', token ? '成功' : '失败');
                } else {
                    console.log('authManager.getToken方法不可用');
                }
            } else {
                console.log('authManager未加载');
            }

            // 如果从authManager获取失败，尝试从localStorage获取
            if (!token) {
                console.log('尝试从localStorage获取token...');
                const authToken = localStorage.getItem('auth_token');
                const oldToken = localStorage.getItem('token');
                token = authToken || oldToken;
                console.log('localStorage中的token - auth_token:', authToken ? '存在' : '不存在');
                console.log('localStorage中的token - token:', oldToken ? '存在' : '不存在');
                console.log('最终选择的token:', token ? '存在' : '不存在');
            }

            if (!token) {
                console.error('无法获取认证token');
                PollutionNotificationService.error('用户未登录，请先登录系统。如果问题持续，请按F12打开控制台查看详细错误信息。');
                return;
            }

            // 直接使用 fetch 进行文件下载，而不是通过 ApiService
            const params = new URLSearchParams({
                customer_id: this.currentCustomerId,
                format: 'excel'
            });

            console.log('导出请求参数:', params.toString());
            console.log('使用token:', token ? '有token' : '无token');
            console.log('token前20字符:', token.substring(0, 20) + '...');

            const requestUrl = `/api/pollution-types/export?${params.toString()}`;
            console.log('请求URL:', requestUrl);

            const response = await fetch(requestUrl, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

            console.log('导出响应状态:', response.status, response.statusText);

            if (response.ok) {
                // 获取文件名
                const contentDisposition = response.headers.get('content-disposition');
                let filename = `pollution_types_${this.currentCustomerId}_${Date.now()}.xlsx`;

                if (contentDisposition) {
                    const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
                    if (filenameMatch && filenameMatch[1]) {
                        filename = filenameMatch[1].replace(/['"]/g, '');
                    }
                }

                console.log('解析到的文件名:', filename);

                // 创建下载链接
                const blob = await response.blob();
                console.log('文件大小:', blob.size, '字节');

                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);

                PollutionNotificationService.success('污染类型数据导出成功');
            } else {
                // 处理错误响应
                let errorData;
                let responseText;
                try {
                    responseText = await response.text();
                    console.error('导出失败 - 原始响应:', responseText);
                    errorData = JSON.parse(responseText);
                } catch (e) {
                    console.error('解析JSON响应失败:', e);
                    errorData = { message: `HTTP ${response.status}: ${response.statusText}`, rawResponse: responseText };
                }

                console.error('导出失败详情:', {
                    status: response.status,
                    statusText: response.statusText,
                    errorData: errorData,
                    requestUrl: requestUrl,
                    tokenUsed: token ? '有token' : '无token'
                });

                // 提供详细的错误信息给用户
                let errorMsg = '导出失败';
                if (errorData && errorData.message) {
                    errorMsg += `: ${errorData.message}`;
                } else if (errorData && errorData.error && errorData.error.message) {
                    errorMsg += `: ${errorData.error.message}`;
                }

                if (response.status === 401 || response.status === 403) {
                    errorMsg += '。请检查您是否已登录，或者重新登录后再试。';
                } else if (response.status === 500) {
                    errorMsg += '。服务器内部错误，请联系管理员。';
                }

                PollutionNotificationService.error(errorMsg);
            }
        } catch (error) {
            console.error('导出异常:', error);
            const errorMsg = this.formatErrorMessage(error.message);
            PollutionNotificationService.error(errorMsg);
        }
    }

    // 工具方法 - 格式化错误信息
    formatErrorMessage(error) {
        if (!error) return '未知错误';

        // 处理对象形式的错误
        if (typeof error === 'object') {
            if (error.message) {
                return this.formatErrorMessage(error.message);
            }
            return JSON.stringify(error);
        }

        // 处理字符串形式的错误
        if (error === '[object Object]') {
            return '操作失败，请稍后重试';
        }

        // 处理网络错误
        if (error.includes('Failed to fetch')) {
            return '网络连接失败，请检查网络设置';
        }

        // 处理超时错误
        if (error.includes('timeout') || error.includes('Timeout')) {
            return '请求超时，请稍后重试';
        }

        return error;
    }

    // 工具方法 - 获取加载状态HTML
    getLoadingHTML() {
        return `
            <div class="text-center py-12">
                <div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
                <p class="mt-4 text-gray-600">正在加载数据...</p>
            </div>
        `;
    }

    // 工具方法 - 获取错误状态HTML
    getErrorHTML(title, message) {
        return `
            <div class="text-center py-12">
                <i class="fas fa-exclamation-triangle text-red-500 text-4xl mb-4"></i>
                <h3 class="text-lg font-medium text-gray-900 mb-2">${title}</h3>
                <p class="text-gray-600 mb-4">${message}</p>
                <button onclick="pollutionTypesManager.loadPollutionTypes()" class="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 transition-colors">
                    <i class="fas fa-redo mr-2"></i>重新加载
                </button>
            </div>
        `;
    }

    // 工具方法 - 设置加载状态
    setLoadingState(loading) {
        this.isLoading = loading;

        // 更新页面加载状态指示器
        const loadingIndicator = document.getElementById('loadingIndicator');
        if (loadingIndicator) {
            loadingIndicator.style.display = loading ? 'block' : 'none';
        }

        // 更新按钮状态
        const buttons = document.querySelectorAll('[data-action="load-data"]');
        buttons.forEach(btn => {
            btn.disabled = loading;
            if (loading) {
                btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>加载中...';
            } else {
                btn.innerHTML = btn.getAttribute('data-original-text') || '加载数据';
            }
        });
    }

    // 工具方法 - 客户端表单验证
    validatePollutionTypeForm(form) {
        const formData = new FormData(form);
        const code = formData.get('typeCode')?.trim();
        const name = formData.get('typeName')?.trim();
        const level = formData.get('typeLevel');
        const parentCode = formData.get('parentTypeCode')?.trim();

        if (!code) {
            return '请输入污染类型代码';
        }

        if (!name) {
            return '请输入污染类型名称';
        }

        if (!level || level < 1 || level > 3) {
            return '请选择有效的层级（1-3）';
        }

        // 代码格式验证
        if (!/^[A-Za-z0-9_\-]+$/.test(code)) {
            return '代码只能包含字母、数字、下划线和连字符';
        }

        // 检查父级代码（层级大于1时必须有父级）
        if (level > 1 && !parentCode) {
            return `层级${level}必须指定父级代码`;
        }

        // 检查层级和父级代码的匹配
        if (level === 1 && parentCode) {
            return '层级1不能有父级代码';
        }

        return null; // 验证通过
    }

    // 工具方法 - 样例表单验证
    validateExampleForm(form) {
        const formData = new FormData(form);
        const content = formData.get('exampleContent')?.trim();
        const confidence = formData.get('confidenceLevel');
        const keywords = formData.get('keywords')?.trim();

        if (!content) {
            return '请输入样例内容';
        }

        if (content.length < 10) {
            return '样例内容至少需要10个字符';
        }

        if (!confidence || confidence < 0 || confidence > 1) {
            return '请输入有效的置信度（0-1之间）';
        }

        if (keywords) {
            const keywordList = keywords.split(',').map(k => k.trim()).filter(k => k);
            if (keywordList.length > 10) {
                return '关键词不能超过10个';
            }
        }

        return null; // 验证通过
    }

    // 工具方法 - 确认对话框
    confirmAction(message, callback) {
        if (confirm(message)) {
            callback();
        }
    }

    async refreshData() {
        if (this.isLoading) {
            PollutionNotificationService.warning('数据正在加载中，请稍候');
            return;
        }

        PollutionNotificationService.info('正在刷新数据...');
        await this.loadPollutionTypes();
        PollutionNotificationService.success('数据刷新完成');
    }
}

// 导出为全局变量，确保main.js可以正确识别
window.PollutionTypesManager = PollutionTypesManager;

// 全局实例
let pollutionTypesManager;

// 延迟创建实例，确保在正确的时机初始化
function createPollutionTypesManager() {
    if (!pollutionTypesManager) {
        console.log('创建污染类型管理器实例...');
        pollutionTypesManager = new PollutionTypesManager();
        window.pollutionTypesManager = pollutionTypesManager;

        // 立即尝试延迟初始化
        setTimeout(() => {
            if (pollutionTypesManager && pollutionTypesManager.delayedInit) {
                pollutionTypesManager.delayedInit();
            }
        }, 100);
    }
    return pollutionTypesManager;
}

// 只在文件直接加载时自动初始化，避免与main.js冲突
if (typeof window !== 'undefined' && !window.pollutionTypesAutoInit) {
    window.pollutionTypesAutoInit = true;

    // 延迟初始化，确保依赖项已加载
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            setTimeout(createPollutionTypesManager, 100);
        });
    } else {
        setTimeout(createPollutionTypesManager, 100);
    }
}

// 全局函数（供HTML调用）- 添加实例检查
// 全局函数定义 - 改进版本，确保函数总是可用
window.showCreatePollutionTypeModal = function() {
    console.log('showCreatePollutionTypeModal called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.showCreatePollutionTypeModal();
    } else {
        console.warn('污染类型管理器未初始化，尝试延迟调用');
        // 尝试延迟调用，给管理器一些初始化时间
        setTimeout(() => {
            if (window.pollutionTypesManager) {
                window.pollutionTypesManager.showCreatePollutionTypeModal();
            } else {
                console.error('污染类型管理器仍未初始化');
                PollutionNotificationService.error('系统未就绪，请刷新页面重试');
            }
        }, 500);
    }
};

window.closePollutionTypeModal = function() {
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.closePollutionTypeModal();
    }
};

window.savePollutionType = function(event) {
    console.log('savePollutionType called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.savePollutionType(event);
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请刷新页面重试');
    }
};

window.editPollutionType = function(typeId) {
    console.log('editPollutionType called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.editPollutionType(typeId);
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请刷新页面重试');
    }
};

window.deletePollutionType = function(typeId) {
    console.log('deletePollutionType called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.deletePollutionType(typeId);
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请刷新页面重试');
    }
};

window.showExamplesModal = function(typeId) {
    console.log('showExamplesModal called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.showExamplesModal(typeId);
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请稍后重试');
    }
};

window.closeExamplesModal = function() {
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.closeExamplesModal();
    }
};

window.showCreateExampleModal = function(typeId) {
    console.log('showCreateExampleModal called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.showCreateExampleModal(typeId);
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请稍后重试');
    }
};

window.closeExampleModal = function() {
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.closeExampleModal();
    }
};

window.editExample = function(exampleId, typeId) {
    console.log('editExample called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.editExample(exampleId, typeId);
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请稍后重试');
    }
};

window.deleteExample = function(exampleId, typeId) {
    console.log('deleteExample called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.deleteExample(exampleId, typeId);
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请稍后重试');
    }
};

window.saveExample = function(event) {
    console.log('saveExample called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.saveExample(event);
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请稍后重试');
    }
};

window.showBatchCreateModal = function() {
    console.log('showBatchCreateModal called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.showBatchCreateModal();
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请刷新页面重试');
    }
};

window.closeBatchCreateModal = function() {
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.closeBatchCreateModal();
    }
};

window.batchCreatePollutionTypes = function() {
    console.log('batchCreatePollutionTypes called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.batchCreatePollutionTypes();
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请刷新页面重试');
    }
};

window.showImportModal = function() {
    console.log('showImportModal called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.showImportModal();
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请刷新页面重试');
    }
};

window.closeImportModal = function() {
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.closeImportModal();
    }
};

window.importPollutionTypes = function(event) {
    console.log('importPollutionTypes called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.importPollutionTypes(event);
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请刷新页面重试');
    }
};

window.exportPollutionTypes = function() {
    console.log('exportPollutionTypes called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.exportPollutionTypes();
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请刷新页面重试');
    }
};

window.searchPollutionTypes = function() {
    console.log('searchPollutionTypes called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.searchPollutionTypes();
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请刷新页面重试');
    }
};

window.refreshData = function() {
    console.log('refreshData called');
    if (window.pollutionTypesManager) {
        window.pollutionTypesManager.refreshData();
    } else {
        console.error('污染类型管理器未初始化');
        PollutionNotificationService.error('系统未就绪，请刷新页面重试');
    }
};

// 版本控制，强制刷新缓存
console.log('PollutionTypesManager loaded - v20250915_10');

// 导出为全局变量，确保main.js可以正确识别
window.PollutionTypesManager = PollutionTypesManager;

// 强制初始化函数 - 确保管理器在页面加载时立即可用
function forceInitPollutionTypesManager() {
    console.log('强制初始化污染类型管理器...');

    // 如果实例不存在，创建实例
    if (!window.pollutionTypesManager) {
        if (typeof PollutionTypesManager !== 'undefined') {
            window.pollutionTypesManager = new PollutionTypesManager();
            console.log('✅ 污染类型管理器实例创建成功');
        } else {
            console.error('❌ PollutionTypesManager类未定义');
            return;
        }
    }

    // 立即执行延迟初始化
    if (window.pollutionTypesManager && typeof window.pollutionTypesManager.delayedInit === 'function') {
        window.pollutionTypesManager.delayedInit().then(success => {
            if (success) {
                console.log('✅ 污染类型管理器延迟初始化成功');
            } else {
                console.warn('⚠️ 污染类型管理器延迟初始化失败');
            }
        }).catch(error => {
            console.error('❌ 污染类型管理器延迟初始化异常:', error);
        });
    }
}

// 在页面加载完成后强制初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', forceInitPollutionTypesManager);
} else {
    // 如果DOM已经加载完成，立即执行
    setTimeout(forceInitPollutionTypesManager, 100);
}

// 暴露强制初始化函数到全局作用域
window.forceInitPollutionTypesManager = forceInitPollutionTypesManager;